<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="registerForm" :rules="rules" class="login-form" auto-complete="on" label-position="left">

      <div class="title-container">
        <h3 class="title">{{getPageTitle()}}用户注册</h3>
      </div>

      <el-form-item prop="inviteCode">
        <span class="svg-container">
          <i class="el-icon-share" />
        </span>
        <el-input
          ref="username"
          v-model="registerForm.inviteCode"
          placeholder="邀请码"
          name="inviteCode"
          type="text"
          tabindex="1"
          auto-complete="off"
        />
      </el-form-item>

      <el-form-item prop="account">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="account"
          v-model="registerForm.account"
          placeholder="用户名"
          name="account"
          type="text"
          tabindex="1"
          auto-complete="off"
          maxlength="20"
        />
      </el-form-item>

      <el-form-item prop="email">
        <span class="svg-container">
          <svg-icon icon-class="email" />
        </span>
        <el-input
          ref="mobile"
          v-model="registerForm.email"
          placeholder="电子邮箱"
          name="email"
          type="text"
          tabindex="1"
          auto-complete="off"
        />
      </el-form-item>

      <el-form-item prop="code">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="code"
          v-model="registerForm.code"
          placeholder="验证码"
          name="code"
          tabindex="2"
          auto-complete="off"
        />
        <span class="show-pwd" @click="sendCode">
          <el-button
            type="primary"
            :disabled="codeLoading"
          >{{btnText}}</el-button>
        </span>
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="registerForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          tabindex="2"
          maxlength="64"
          auto-complete="on"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>

      <el-button :loading="loading" class="register-button" @click="submitRegister()">注册</el-button>
      <div style="text-align: center">
        <el-link :underline="false" type="warning" class="login-tips" @click="jumpLogin">已有账号？点击登录</el-link>
      </div>

    </el-form>

  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import {deepCopy, isEmail, isMobile} from "@/utils";
import request from "@/utils/request";
import {sendEmailCode, sendMobileCode} from "@/api/login";
import getPageTitle from "../../utils/get-page-title";

export default {
  name: 'Login',
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码最少为6位'))
      } else {
        callback()
      }
    }
    const validateEmail = (rule,value,callback) => {
      if (!isEmail(value)) {
        callback(new Error('请填写正确的邮箱格式'))
      } else {
        callback()
      }
    }

    // 校验用户名是否有重复的
    const checkAccount = (rule, value, callback) => {
      request({
        url: '/login/checkAccount',
        method: 'get',
        params:{
          account : value,
        },
        handleError: true,
      }).then(res=>{
        if(res.error !== 0){
          callback(new Error(res.message));
        }else{
          callback();
        }
      })
    };

    const checkEmail = (rule, value, callback) => {
      request({
        url: '/login/checkEmail',
        method: 'get',
        params:{
          account : value,
        },
        handleError: true,
      }).then(res=>{
        if(res.error !== 0){
          callback(new Error(res.message));
        }else{
          callback();
        }
      })
    };

    return {
      registerForm: {
        inviteCode: '', // 邀请码
        account: '', // 用户名
        password: '',
        email: '', // 手机号
        code: '',
      },
      loading: false,
      codeLoading: false,
      btnText : '获取验证码',
      passwordType: 'password',
      rules:{
        inviteCode: [
          { required: true,message: "请填写邀请码"  ,trigger: 'blur' }
        ],
        account: [
          { required: true,message: "请填写用户名"  ,trigger: 'blur' },
          { min: 3, max:20, message: "用户名至少3位,最多20位"  ,trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_]+$/ , message: '用户名只能输入英文数字中文,特殊符号只能输入下划线"_"',trigger: 'blur' },
          { validator:checkAccount,trigger: 'blur' },
        ],
        email: [
          { required: true, validator:validateEmail ,trigger: 'blur' }, // 校验邮箱格式
          { validator:checkEmail ,trigger: 'blur' }, // 校验邮箱是否重复
        ],
        code: [
          { required: true,message: "请填写验证码"  ,trigger: 'blur' },
        ],
        password: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ]
      },
    }
  },
  methods: {
    getPageTitle,
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    // 注册
    submitRegister(){
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          const postData = deepCopy(this.registerForm)
          request({
            url: '/login/register',
            method: 'post',
            data: postData,
            handlerError: true,
          })
            .then(res=>{
              if(res.error === 0){
                this.$successMessage('注册成功')
                setTimeout(()=>{
                  this.jumpLogin();
                },1000)
              }else{
                this.$errorMessage(res.message)
              }
              this.loading = false;
            })
        }
      })
    },
    // 发送验证码
    sendCode(){
      if(!isEmail(this.registerForm.email)){
        this.$errorMessage('邮箱格式不正确')
        return;
      }
      this.codeLoading = true
      this.btnText = '请稍后...'
      // 发送请求
      sendEmailCode(this.registerForm.email,'register')
        .then(res=>{
          if(res.error === 0){
            this.doLoop();
            this.$successMessage('验证码已发送');
          }else{
            this.codeLoading = false;
            this.$errorMessage(res.message);
            this.btnText = '获取验证码'

          }
        })
    },
    // 倒数验证码
    doLoop(seconds = 60){
      this.btnText = seconds + "s后获取";
      let countDown = setInterval(()=>{
        if(seconds > 0){
          this.btnText = seconds + "s后获取";
          seconds--;
        }else{
          this.btnText = "获取验证码";
          this.codeLoading = false;
          clearInterval(countDown);
        }
      },1000)
    },
    // 跳转到注册页面
    jumpLogin(){
      this.$router.push({
        path: '/'
      })
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;
$font_color1: #E3672A;
$font_color2: #283443;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;


    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $font_color2;
      height: 47px;
      caret-color: $font_color2;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px #ffffff inset !important;
        -webkit-text-fill-color: $bg !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid #ccc;
    //background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
  .login-button{
    background-color: $font_color1;
    color: #fff;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;
$bg-image:"../../assets/images/register-bg.png";
$font_color1: #E3672A;

.login-container {
  min-height: 100%;
  width: 100%;
  background-image: url($bg-image);
  background-repeat:no-repeat;
  background-size: 100% 100%;
  //background-attachment: fixed;
  //background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    background-color: #ffffff;
    padding: 30px 50px;
    //padding: 160px 35px 0;
    margin: 160px auto;
    overflow: hidden;
    border-radius: 5px;
    box-shadow:darkgrey 10px 10px 30px 5px;

  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $font_color1;
      margin: 0 auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}

.login-tips{
  margin-top: 10px;
  text-align: center;
  color: #FF9C07;
  font-size: 12px;
}
.register-button{
  width: 100%;
  margin-left: 0;
  color: #FFFFFF;
  background-color: #716d62;
  height: 45px;
  font-size: 14px;
}
</style>
